package com.anytrek.clouduser.service.impl;

import com.anytrek.cloudcommon.utils.ApiResult;
import com.anytrek.clouduser.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.anytrek.cloudcommon.entity.UsersEntity;
import com.anytrek.cloudcommon.mapper.UsersMapper;
import io.seata.spring.annotation.datasource.EnableAutoDataSourceProxy;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author Alex2
* @description 针对表【t_users】的数据库操作Service实现
* @createDate 2025-08-22 10:48:54
*/
@Log4j2
@Service
@RequiredArgsConstructor
@EnableAutoDataSourceProxy
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersEntity>
    implements UsersService {

    private static final String TAG = "Alex";

    @Override
    public ApiResult insertUser(String username, String password, Integer age, Integer balance) {
        UsersEntity usersEntity = lambdaQuery().eq(UsersEntity::getUsername, username).one();
        if (usersEntity != null) {
            log.error("{}:{}", TAG, "该用户名已存在，插入失败");
            return ApiResult.error("该用户名已存在，插入失败");
        }
        UsersEntity user = new UsersEntity(null, username, password, age, balance);
        boolean save = save(user);
        if (!save) {
            log.error("{}:{}", TAG, "插入用户失败");
            return ApiResult.error("插入用户失败");
        }
        log.info("{}:{}", TAG, "插入用户成功");
        return ApiResult.success("插入用户成功");
    }

    @Override
    public ApiResult getUserById(Integer id) {
        UsersEntity usersEntity = lambdaQuery().eq(UsersEntity::getId, id).one();
        if (usersEntity == null) {
            log.error("{} : {}", TAG, "用户不存在");
            return ApiResult.error("用户不存在");
        }
        log.info("{} : usersEntity = {}", TAG, usersEntity);
        return ApiResult.success("用户查询成功", usersEntity);
    }

    /**
     * @ Author: Alex
     * @ Description: 项目实战-分布式事务-扣减余额
     */
    @Transactional
    @Override
    public ApiResult deductBalance(Integer id, Integer amount) {
        UsersEntity usersEntity = lambdaQuery().eq(UsersEntity::getId, id).one();
        if (usersEntity == null) {
            log.error("{} : {}", TAG, "用户不存在");
            throw new RuntimeException("用户不存在");
        }
        if (usersEntity.getBalance() < amount) {
            throw new RuntimeException("余额不足");
        }
        boolean update = lambdaUpdate()
                .eq(UsersEntity::getId, usersEntity.getId())
                .set(UsersEntity::getBalance, usersEntity.getBalance() - amount)
                .update();
        if (!update) {
            log.info("{}:{}:{}", TAG, id, "扣减余额失败");
            throw new RuntimeException("扣减余额失败");
        }
        log.info("{}:{}:{}", TAG, id, "扣款成功");
        return ApiResult.success("扣款成功");
    }
}